<?php

{$AUTO_GENERATOR_INCLUDE_HEADER_TEMPLATE}

defined('_JEXEC') or die;

class {$AUTO_GENERATOR_COMPONENT|capitalize}Model{$AUTO_GENERATOR_MODELS|capitalize} extends JModelList {

    public function __construct($config = array()) {
        
        if (empty($config['filter_fields'])) {
            $config['filter_fields'] = array(
                {$AUTO_GENERATOR_MODELS_FILTER_FIELDS}
            );
        }

        parent::__construct($config);
    }

    protected function populateState($ordering = null, $direction = null) {
        $app = JFactory::getApplication();

        $search = $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search');
        
        $this->setState('filter.search', $search);
        
        parent::populateState('{$AUTO_GENERATOR_PRIMARY_KEY_FIELD}', 'asc');
    }

    protected function getStoreId($id = '') {
        // Compile the store id.
        $id .= ':' . $this->getState('filter.search');

        return parent::getStoreId($id);
    }

    public function getItems() {
        $aItems = parent::getItems();
        
        return $aItems;
    }

    protected function getListQuery() {
        $db = $this->getDbo();
        $query = $db->getQuery(true);

        $query->select($this->getState('list.select', '*'))
                ->from('#__{$AUTO_GENERATOR_SQL_TABLE_NAME}');

        // For search.
        $search = $this->getState('filter.search');
        
        if (!empty($search)) {
            if (stripos($search, 'id:') === 0) {
                $query->where('{$AUTO_GENERATOR_PRIMARY_KEY_FIELD} = ' . (int) substr($search, 3));
            } else {
                $search = $db->Quote('%' . $db->escape($search, true) . '%');
                $query->where('({$AUTO_GENERATOR_PRIMARY_KEY_FIELD} LIKE ' . $search . ')');
            }
        }
        
        // For ordering.
        $orderCol = $this->state->get('list.ordering', '{$AUTO_GENERATOR_PRIMARY_KEY_FIELD}');
        $orderDirn = $this->state->get('list.direction', 'asc');
        $query->order($db->escape($orderCol . ' ' . $orderDirn));
        
        return $query;
    }

}
